import { Checkbox, message, Form, Input, Card, Select } from 'antd';
import React, { useState } from 'react';
import { Link, SelectLang } from 'umi';
import { getPageQuery } from '@/utils/utils';
import logo from '@/assets/logo.svg';
import { LoginParamsType, abpIsTenantAvailable } from '@/services/login';
import { BulbTwoTone } from '@ant-design/icons';
// import Footer from '@/components/Footer';
import LoginFrom from './components/Login';
import styles from './style.less';
import * as Request from '@/services/Request';

const { Username, Password, Submit } = LoginFrom;
const apiURL = "/api/TokenAuth/Authenticate";

/**
 * 此方法会跳转到 redirect 参数所在的位置
 */
const replaceGoto = () => {
  const urlParams = new URL(window.location.href);
  const params = getPageQuery();
  let { redirect } = params as { redirect: string };
  if (redirect) {
    const redirectUrlParams = new URL(redirect);
    if (redirectUrlParams.origin === urlParams.origin) {
      redirect = redirect.substr(urlParams.origin.length);
      if (redirect.match(/^\/.*#/)) {
        redirect = redirect.substr(redirect.indexOf('#'));
      }
    } else {
      window.location.href = '/';
      return;
    }
  }
  window.location.href = urlParams.href.split(urlParams.pathname)[0] + (redirect || '/');
};

const Login: React.FC<{}> = () => {
  const [] = useState<API.LoginStateType>({});
  const [submitting, setSubmitting] = useState(false);

  const [autoLogin, setAutoLogin] = useState(true);

  const handleSubmit = async (values: LoginParamsType) => {
    setSubmitting(true);
    try {
      // 登录
      //const msg = await fakeAccountLogin({ ...values, type });
      await abpIsTenantAvailable({ tenancyName: values.tenant }).then(async (resp) => {
        if (resp.success) {
          localStorage.setItem('tenantId', resp.result.tenantId);
          localStorage.setItem('tenantName', values.tenant);
          values.tenant = resp.result.tenantId;
          Request.post(apiURL, values).then((response) => {
            if (response) {
              if (response.success) {
                message.success('登录成功！');
                localStorage.setItem('access-token', response.result.accessToken);
                replaceGoto();
              }
              else {
                message.error(response.error.details);
              }
            }
          });
        }
      });
    } catch (error) {
      message.error('登录失败，请重试！');
    }
    setSubmitting(false);
  };

  return (
    <div className={styles.container}>
      <div className={styles.lang}>
        <SelectLang />
      </div>
      <div className={styles.content}>

        <div className={styles.main}>
          <Card hoverable>
            <div className={styles.top}>
              <div className={styles.header}>
                <Link to="/">
                  <img alt="logo" className={styles.logo} src={logo} />
                  <span className={styles.title}>OPERP</span>
                </Link>
              </div>
              <div className={styles.desc}>简单快捷的管理企业资源</div>
            </div>
            <LoginFrom onSubmit={handleSubmit}>
              <Form.Item
                name='tenant'>
                <Input placeholder="请输入账号" prefix={<BulbTwoTone />} size="large" />
              </Form.Item>
              <Username
                name="UserNameOrEmailAddress"
                placeholder="用户名: admin or user"
                rules={[
                  {
                    required: true,
                    message: '请输入用户名!',
                  },
                ]}
              />
              <Password
                name="password"
                placeholder="密码: 6~12个字符"
                rules={[
                  {
                    required: true,
                    message: '请输入密码！',
                  },
                ]}
              />
              <div>
                <Checkbox checked={autoLogin} onChange={(e) => setAutoLogin(e.target.checked)}>
                  自动登录
              </Checkbox>
              </div>
              <Submit loading={submitting}>登录</Submit>
            </LoginFrom>
          </Card>
        </div>
      </div>

    </div>
  );
};

export default Login;
